{{csrf_field()}}
<div class="layui-row layui-col-space20">
    <div class="layui-col-md4">

        @include('admin.miniprogram.page.navcomponents')
    </div>
    <div class="layui-col-md4">

        @include('admin.miniprogram.page.phonemain')
    </div>
    <div class="layui-col-md4 ">

        @include('admin.miniprogram.page.editor')
    </div>
</div>
<textarea id="edit_image" style="display: none;"></textarea>
@section('script')
    <link rel="stylesheet" href="{{ asset('static/admin/iconfonts/mdi/css/materialdesignicons.min.css') }}">
    <link rel="stylesheet" href="{{ asset('static/admin/css/diynew.css') }}">

    <script src="{{ asset('static/admin/js/jquery.min.js') }}"></script>
    <script src="{{ asset('static/admin/js/ddsort/ddsort.js') }}"></script>
    <script>
        var BASE_URL='';
        var diyData = {
            items: {
                page: {
                    id: 'page',
                    type: 'page',
                    name: '页面设置',
                    params: {
                        name: '页面名称',
                        title: '页面标题',
                        share_title: '分享标题'
                    },
                    style: {
                        titleTextColor: 'black',
                        titleBackgroundColor: '#ffffff'
                    }
                }
            }
        };
        var defaultData = {
            search: {
                name: '搜索框',
                params: {
                    'placeholder': '请输入关键字进行搜索2'
                },
                style: {
                    textAlign: 'left',
                    searchStyle: ''
                }
            },
            blank: {
                name: '辅助空白',
                style: {
                    height: '20',
                    background: '#ffffff'
                }
            },
            guide: {
                name: '辅助线',
                style: {
                    background: '#ffffff',
                    lineStyle: 'solid',
                    lineHeight: '1',
                    lineColor: "#000000",
                    paddingTop: 10
                }
            },
            video: {
                name: '视频组',
                params: {
                    videoUrl: 'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400',
                    poster: BASE_URL + 'assets/user/img/diy/video_poster.jpg'
                },
                style: {
                    paddingTop: '0',
                    height:'180',


                }
            },
            notice: {
                name: '公告组',
                params: {
                    text: '这里是第一条自定义公告的标题',
                    icon: "{{ asset('static/admin/images/notice.png') }}"
                },
                style: {
                    paddingTop: '4',
                    background: '#ffffff',
                    textColor: '#000000'
                }
            },
            richText: {
                name: '富文本',
                params: {
                    content: '这里是富文本的内容'
                },
                style: {
                    paddingTop: '0',
                    paddingLeft: '0',
                    background: '#ffffff'
                }
            },
            banner: {
                name: '图片轮播',
                style: {
                    btnColor: '#ffffff',
                    btnShape: 'round',
                    heightimage:'',

                },
                data: [{
                    imgUrl: 'http://min3.test/assets/user/img/diy/banner_01.jpg',
                    linkUrl: '',
                    advise: '建议尺寸750x360'
                },
                    {
                        imgUrl: 'http://min3.test/assets/user/img/diy/banner_01.jpg',
                        linkUrl: '',
                        advise: '建议尺寸750x360'
                    }]
            },
        };

        layui.use(['layer','carousel', 'form','formSelects','laytpl','colorpicker', 'slider'], function(){
            var layer = layui.layer,
                slider = layui.slider, //滑块

                laytpl = layui.laytpl,
                form =layui.form,
                colorpicker = layui.colorpicker;

            $("body").on("click", ".skysave", function ()
            {
                var array = {11:"a",22:"b"};
                $.ajax({
                    type : 'POST',
                    url:  '/check/testPost',
                    contentType: "application/x-www-form-urlencoded",
                    data: {"list": array},
                    success : function(data) {
                    }
                });

            });



            var _editor = UE.getEditor("edit_image",{
                initialFrameWidth:800,
                initialFrameHeight:300,
                zIndex:19891026,
            });
            _editor.ready(function (){
                _editor.hide();
                _editor.addListener('beforeInsertImage',function(t,arg){
                    console.log(arg);
                    console.log(t);
                    var obj = _editor.queryCommandValue("serverparam");
                    if(obj.type == "upload-image"){
                        if(arg.length>1){
                            layer.msg("最多只能选择1张图片，请重新选择");
                            return false;
                        }
                        if(arg.length>0) {
                            var uploadImageTd = obj.uploadImageItem.parent().find(".layui-upload-list");
                            console.log(uploadImageTd);
                            uploadImageTd.find('img').attr('src',arg[0].src);
                            uploadImageTd.find('input').val(arg[0].src).change();
                            console.log(111);
                            //uploadImageTd.find('input').val(arg[0].src).change();
                            uploadImageTd.show();

                            /*var itemId = obj.uploadImageItem.parents(".editorlist").data("itemid"),
                                bind = obj.uploadImageItem.data('bind'),
                                itemIndex=bind.split('.'),
                                val = arg[0].src;
                            console.log(itemId);

                            bindItemData(itemId, itemIndex, val);
                            updateItemData(itemId);*/

                        }else{
                            layer.msg("请先选择图片");
                            return false;
                        }
                    }
                    return true;
                });
            });

            $("body").on("click", ".upload-image", function () {

                //此处进行初始化
                var obj = _editor.queryCommandValue("serverparam");
                obj.type = "upload-image";
                obj.uploadImageItem = $(this);
                var uploadImage = _editor.getDialog("insertimage");
                console.log(obj);

                uploadImage.open();
            });




            //监听提交
            form.on('submit(post-submit)', function(data)
            {

            });
            
            $.each(diyData.items,function (index,item) {
                console.log(item);
                var getTpl = $('#tpl_diy_'+item.type).html();
                console.log(getTpl);
                laytpl(getTpl).render(item, function(html){
                    if(item.id=='page')
                    {
                        console.log(item.id);
                        $("#diy-page").prop('outerHTML',html).addClass('selected');
                    }
                    else
                    {
                        console.log(item.id);
                        $('#phone-main').append(html)
                    }

                    //$('#phone-main').append(html)
                   // console.log(html);
                    //view.innerHTML = html;
                });

                var getTpl = $('#tpl_editor_'+item.type).html();
                console.log(getTpl);
                laytpl(getTpl).render(item, function(html){

                    if(item.id=='page')
                    {

                        $('.editorbox').html(html);
                    }
                });

                form.render();

            });

            $('.editorbox').DDSort({
                target: '.form-item',
                delay: 50,
                floatStyle: {
                    'border': '1px solid #ccc',
                    'background-color': '#fff'
                },
                // 由于 transform 的影响，对于类似 bootstrap 这样用了 transform 的元素，
                // 需要手动处理拖拽元素的位置，如下
                move: function (left, top) {
                    $(this).css('left', left);
                    $(this).css('top', top );
                },
                // 延时处理，默认为 50 ms，防止手抖点击 A 链接无效
                up: function() {
                    console.log($(this).parent())

                }

            });


            $('#phone-main').DDSort({
                target: '.drag',
                delay: 50,
                floatStyle: {
                    'border': '1px solid #ccc',
                    'background-color': '#fff'
                },
                // 由于 transform 的影响，对于类似 bootstrap 这样用了 transform 的元素，
                // 需要手动处理拖拽元素的位置，如下
                move: function (left, top) {
                    $(this).css('left', left);
                    $(this).css('top', top );
                },
                // 延时处理，默认为 50 ms，防止手抖点击 A 链接无效
                up: function() {
                   console.log($(this).parent())

                }

            });




            //删除
            $("body").on("click", ".btn-del", function ()
            {
                var $this = $(this),
                    itemId = $this.parents(".drag").data('itemid');
                console.log(itemId);
                layer.confirm('确定要删除吗？',function(index) {
                        $this.parents(".drag").remove();
                        $('.editorbox').html("");

                        layer.close(index);
                        delItemId(itemId)
                    });
                console.log(diyData);
            });

            $("body").on("click", ".createSubItem", function ()
            {
                var $this = $(this),
                    itemId = $this.parents(".editorlist").data('itemid'),
                    item = diyData.items[itemId],
                    itemType = item.type;
                console.log(defaultData[item.type].data[0]);
                console.log(addItemData(itemId,itemType,defaultData[item.type].data[0]));

                console.log(itemId);



                var getTpl = $('#tpl_editor_'+itemType).html();
                laytpl(getTpl).render(item, function(html){
                    $('.editorbox').html(html)
                    console.log(html);


                    //view.innerHTML = html;
                });

                console.log(diyData);
            });
            //
            //删除子元素
            $("body").on("click", ".item-delete", function ()
            {
                var $this = $(this),
                    itemId = $this.parents(".editorlist").data('itemid'),
                    subItemId = $this.parents(".form-item").data('id');
                console.log(itemId); console.log(subItemId);
                console.log(diyData.items[itemId]["data"]);

               // return false;
                layer.confirm('确定要删除吗？',function(index) {
                    $this.parents(".form-item").remove();


                    layer.close(index);
                    delSubItemId(itemId,subItemId);
                    //delete diyData.items[itemId]["data"][subItemId];
                });
                console.log(diyData);
            });


            //切换选中
            $("body").on("click", ".optional", function ()
            {
                var itemId = $(this).data('itemid'),
                    item = diyData.items[itemId],
                    getTpl = $('#tpl_editor_'+item.type).html();

                laytpl(getTpl).render(item, function(html){
                    $('.editorbox').html(html);
                    if(item.type == 'richText')
                    {
                        richText(item.id);
                        console.log(item.type);
                    }
                });
                form.render();
                $('.optional').removeClass("selected");
                $('#diy-'+itemId).addClass("selected");

            });

            //增加新元素
            $("body").on("click", "nav.special", function ()
            {
                var _this= $(this),
                    type=_this.data("type"),
                    diyItemId = getItemId();

                console.log(diyItemId);

                //此处数据进行合并
                var item = diyData.items[diyItemId]=$.extend(true, {},{id: diyItemId,type: type},defaultData[type]);

                var getTpl = $('#tpl_diy_'+type).html();
                laytpl(getTpl).render(item, function(html){
                    $('#phone-main').append(html)
                    console.log(html);


                    //view.innerHTML = html;
                });

                if (item.hasOwnProperty('data')) {

                    var subItem=[];
                    var subItemFormate=[];
                    $.each(item.data,function (key,val) {
                        console.log(val);
                        console.log(item.type);
                        //var subItemData = addItemData(item.id, item.type, val);
                        subItem.push(addItemData(item.id, item.type, val));
                        //subItemFormate[subItemData.id] = subItemData;
                        //diyData.items[item.id]["data"]=null;
                        //diyData.items[item.id]["data"] = addItemData(item.id, item.type, val);

                    })
                    //console.log(subItemFormate);
                   // console.log(subItem);
                    diyData.items[item.id]['data']=subItem;

                    console.log('----sky');

                }

                var getTpl = $('#tpl_editor_'+type).html();
                laytpl(getTpl).render(item, function(html){
                    $('.editorbox').html(html)
                    console.log(html);


                    //view.innerHTML = html;
                });

               // console.log(diyData);


               console.log(diyData);



                sliderData(diyItemId);
                if(type=='richText')
                {
                    richText(item.id);
                }
                $('.optional').removeClass("selected");
                $('#diy-'+diyItemId).addClass("selected");



                form.render();
            });


            // 绑定input修改事件
            $(".editorbox").on('input propertychange change', '[data-bind]', function()
            {
                console.log(111111111111);
                var itemId = $(this).parents('.editorlist').data('itemid'),
                        item = diyData.items[itemId],
                        bind = $(this).data('bind'),
                        itemIndex=bind.split('.'),
                        val = $(this).val();

                console.log(itemId);
                console.log(bind);
                console.log(item);
                console.log(itemIndex);
                console.log(val);
                bindItemData(itemId, itemIndex, val);
                console.log(diyData);
                updateItemData(itemId);

            });

//滑动
            $(".upload-image input").on('change', function()
            {
                var $this = $(this);
                $this.next('input').val($this.val());

            });
            //滑动
            $(".editorbox").on('input propertychange change', 'input[type=range]', function()
            {
                var $this = $(this);
                $this.next('input').val($this.val());

            });
            //滑动输入框
            $(".editorbox").on('input propertychange change', '.rangeinput', function()
            {
                var $this = $(this);
                $this.prev('input').val($this.val());
            });



            form.on('radio(radio)', function(data)
            {
                var itemId = $(this).parents('.editorlist').data('itemid'),
                    bind = $(this).data('bind'),
                    itemIndex=bind.split('.'),
                val = data.value;

            console.log(data.elem); //得到radio原始DOM对象
            console.log(data.value); //被点击的radio的value值
            bindItemData(itemId, itemIndex, val);
            updateItemData(itemId);
        });


        //生成itemID
        function getItemId()
        {
            return 'n' + Math.random().toString().substr(3);
        }
            function delSubItemId(itemId,subItemId)
            {
                delete diyData.items[itemId]["data"][subItemId];
            }
        /**
         * 生成json
         * @param itemId
         */
        function delItemId(itemId)
            {
                delete diyData.items[itemId];
            }

            /**
             * 重新生成数据
             * @param itemId
             */
            function updateItemData(itemId)
            {
                var item = diyData.items[itemId],
                    itemType = diyData.items[itemId]["type"],
                    getTpl=$("#tpl_diy_"+itemType).html();

                console.log(item);
                console.log(itemType);
                laytpl(getTpl).render(item, function(html){
                    $("#diy-"+itemId).prop('outerHTML',html).addClass('selected');
                    console.log(html);
                });
                $('.optional').removeClass("selected");
                $("#diy-"+itemId).addClass('selected');
                if (item.hasOwnProperty('foo')) {
                    // your code here
                }
               // addItemData(itemId, itemType);
                
            }

            /**
             * 数据绑定
             * @param itemId
             * @param itemIndex
             * @param val
             */
            function bindItemData(itemId, itemIndex, val)
            {
                var item = diyData.items[itemId][itemIndex[0]];
                switch (itemIndex.length) {
                    case 1:
                        item = val;
                        break;
                    case 2:
                        item[itemIndex[1]] = val;
                        break;
                    case 3:
                        item[itemIndex[1]][itemIndex[2]] = val;
                        break;
                    case 4:
                        item[itemIndex[1]][itemIndex[2]][itemIndex[3]] = val;
                        break;
                }
            }

            /**
             * 滑块
             * @param itemId
             */
            function sliderData(itemId) {
                slider.render({
                    elem: '#slide'+itemId,
                    min: 0, //最小值                    ,
                    max: 1200, //最大值                    ,
                    value: 20, //初始值
                    theme: '#1E9FFF', //主题色
                    input: true, //输入框
                    change: function(value){
                        console.log(value) //动态获取滑块数值
                        var bind = $('#slide'+itemId).data('bind'),
                            itemIndex=bind.split('.');
                        bindItemData(itemId, itemIndex, value);
                        updateItemData(itemId);

                    }
                });
            }

            /**
             * 生成富编辑器
             * @param itemId
             */
            function richText(itemId) {

                UE.delEditor("richText"+itemId );
                var _editor = UE.getEditor("richText"+itemId ,{
                    initialFrameHeight:300,
                    zIndex:1,
                    toolbars: [
                        [ 'source', 'undo', 'redo', 'bold','fontfamily','fontsize',
                            'paragraph', 'simpleupload','insertimage'
                        ]
                    ]
                });
                _editor.addListener("contentChange",function(){
                    console.log('内容改变:'+_editor.getContent());
                    $('#diy-'+itemId+' .diy-richText').html(_editor.getContent());
                    diyData.items[itemId]["params"]["content"] = _editor.getContent();
                    console.log(diyData);
                });
            }
            
            function selectedSingle() {
                
            }
            
            function addItemData(itemId, itemType ,subItem) {
               // console.log(subItem);
               /* return false;
                var item = diyData.items[itemId];
                console.log(item);
                var de=defaultData[itemType];
                console.log(de);

                var defaultItemData =defaultData[itemType].data[0];*/
                return $.extend(true, {},{id: getItemId()},subItem);
               // console.log(item);
               // diyData.items[itemId]["data"].push(item);


             //   console.log(diyData);
                /*var dataId = this.newDataId(),
                    data = {},
                    defaultItemData = defaultData[itemType].data[0];
                data[dataId] = $.extend(true, {
                        dataId: dataId
                    },
                    defaultItemData);
                diyData.items[itemId].data[dataId] = data[dataId];
                // 记录dataNum
                if (diyData.items[itemId].hasOwnProperty('dataNum')) diyData.items[itemId].dataNum++;
                return data;*/
            }

        });
    </script>
@endsection